define(function (require, exports, module) {
    const {DrawPolygon} = require('../../../../map/mapbox/modes/DrawPolygon.js').onload();
    const Constants = require('../../../../map/mapbox/modes/utils/constants.js').onload();
    const isEventAtCoordinates = require('../../../../map/mapbox/modes/utils/is_event_at_coordinates.js').onload();
    const doubleClickZoom = require('../../../../map/mapbox/modes/utils/double_click_zoom.js').onload();

    const turf = window.turf
    const ElMessage = window.ELEMENT.Message

    function onload() {
        const DrawBuilding = Object.assign({}, DrawPolygon)

        DrawBuilding.onSetup = function(opts) {
            const polygon = this.newFeature({
                type: Constants.geojsonTypes.FEATURE,
                properties: {},
                geometry: {
                    type: Constants.geojsonTypes.POLYGON,
                    coordinates: [[]]
                }
            });

            this.addFeature(polygon);

            this.clearSelectedFeatures();
            doubleClickZoom.disable(this);
            this.updateUIClasses({ mouse: Constants.cursors.ADD });
            this.activateUIButton(Constants.types.POLYGON);
            this.setActionableState({
                trash: true
            });

            return {
                parent: opts.parent,
                brothers: opts.brothers,
                polygon,
                currentVertexPosition: 0
            };
        };

        DrawBuilding.clickAnywhere = function(state, e) {
            const currentPoint = turf.point([e.lngLat.lng, e.lngLat.lat]);

            const parent = state.parent
            if (!turf.booleanPointInPolygon(currentPoint, parent, {ignoreBoundary: false})) {
                ElMessage.error('不能在父网格之外绘制楼栋! ')
                return false
            }

            const brothers = state.brothers.features
            for (let i = 0; i < brothers.length; i++) {
                const brother = brothers[i]
                if (turf.booleanPointInPolygon(currentPoint, brother, {ignoreBoundary: true})) {
                    ElMessage.error('不能在其他楼栋之上绘制楼栋! ')
                    return false
                }
            }

            if (state.currentVertexPosition > 0 && isEventAtCoordinates(e, state.polygon.coordinates[0][state.currentVertexPosition - 1])) {
                return this.changeMode(Constants.modes.SIMPLE_SELECT, { featureIds: [state.polygon.id] });
            }
            this.updateUIClasses({ mouse: Constants.cursors.ADD });
            state.polygon.updateCoordinate(`0.${state.currentVertexPosition}`, e.lngLat.lng, e.lngLat.lat);
            state.currentVertexPosition++;
            state.polygon.updateCoordinate(`0.${state.currentVertexPosition}`, e.lngLat.lng, e.lngLat.lat);
        };

        return {
            DrawBuilding
        }
    }

    module.exports = {
        onload
    }
});
